#include "yellow_line_detector.h"
#include <windows.h>
#include "logger.h"

using namespace cv;
using namespace std;

void yellow_line_detector::init()
{
    char file_ini[64] = CONFIG_FILE_PATH ;
	char param_name[64] = "yellow_line";
	red_max = GetPrivateProfileIntA(param_name,   "rMax", -1, file_ini);
	red_min = GetPrivateProfileIntA(param_name,   "rMin", -1, file_ini);
	green_max = GetPrivateProfileIntA(param_name, "gMax", -1, file_ini);
	green_min = GetPrivateProfileIntA(param_name, "gMin", -1, file_ini);
	blue_max = GetPrivateProfileIntA(param_name,  "bMax", -1, file_ini);
	blue_min = GetPrivateProfileIntA(param_name,  "bMin", -1, file_ini);

	LOG(INFO) << "red_max: " << red_max << ", ";
	LOG(INFO) << "red_min: " << red_min << ", ";
	LOG(INFO) << "green_max " << green_max << ", ";
	LOG(INFO) << "green_min " << green_min << ", ";
	LOG(INFO) << "blue_max " << blue_max << ", ";
	LOG(INFO) << "blue_min " << blue_min << ", ";

}

//轮胎不会是黄色
double yellow_line_detector::detect(cv::Mat img, std::vector<cv::Point> pts)
{
//	double time0 = static_cast<double>(getTickCount());//记录起始时间

	Mat mask = Mat::zeros(img.size(), CV_8UC3);
	fillPoly(mask, pts, Scalar(255, 255, 255), 8, 0);

	Mat tmp = mask & img;
	Rect search_rect = boundingRect(pts);

	int total_num = 0;
	int count = 0;
//	cout << "search_rect = " << search_rect << endl;

	Mat yellow = Mat::zeros(img.size(), CV_8UC1);
	for (int i = 0; i < search_rect.width; i++) {
		for (int j = 0; j < search_rect.height; j++) {
            cv::Vec3b bgr = tmp.at<cv::Vec3b>(search_rect.y + j, search_rect.x + i);
			if (is_yellow(bgr)) {
				count++;
				yellow.at<unsigned char>(search_rect.y + j, search_rect.x + i) = 255;
			}
            if(!is_black(bgr)){
                total_num++;
            }

		}
	}

#if 0
    cv::resize(tmp, tmp, cv::Size(720, 576));
	cv::resize(yellow, yellow, cv::Size(720, 576));
	cv::resize(img, img, cv::Size(720, 576));
    imshow("tmp", tmp);
	imshow("yellow", yellow);
	imshow("img", img);
	waitKey(0);
#endif

	double percent = (double)count/ total_num;
	//cout << "count = " << count << endl;
	//cout << "total_num =" << total_num << endl;
	//cout << "percent = " << percent <<endl;
	
	//time0 = ((double)getTickCount() - time0) / getTickFrequency();
	//cout << "use time：" << time0 << "s" << endl;
	return percent;
}

bool yellow_line_detector::is_yellow(cv::Vec3b bgr)
{
	//cout << "B: " << (unsigned int)bgr.val[0] << ", ";
	//cout << "G: " << (unsigned int)bgr.val[1] << ", ";
	//cout << "R: " << (unsigned int)bgr.val[2] << endl;
	if ((bgr.val[2] >= red_min) && (bgr.val[1] >= green_min) && (bgr.val[0] >= blue_min) && \
		(bgr.val[2] <= red_max) && (bgr.val[1] <= green_max) && (bgr.val[0] <= blue_max)) {
		return true;
	}
    return false;
}

bool yellow_line_detector::is_black(Vec3b bgr)
{
    if(0 == bgr.val[0]  &&0 == bgr.val[1]  &&0 ==bgr.val[2])
    {
        return true;
    }
    return false;
}
